#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: capture_get_dir.py
# Author: ChenChangSong
# Date: 2025-08-24


"""
功能描述: 获取测试用例目录（注意：获取不到IPA导入的部分目录）
"""

import sys
import os
from comm.common_code import *

def capture_get_dir():
    """获取测试用例目录"""
    excel_data = get_excel_data()
    url = f"https://www.tapd.cn//api/entity/filter/get_fields?from=tcase&workspace_id={excel_data['项目ID']}&selected_workspace_id={excel_data['项目ID']}&with_workitem_type_status_map=0"
    payload={}
    headers = {
    'authority': 'www.tapd.cn',
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cookie': excel_data['Cookie'],
    'referer': f'https://www.tapd.cn/{excel_data["项目ID"]}/sparrow/tcase/tcase_list',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.554.400 QQBrowser/19.5.6663.400',
    'x-requested-with': 'XMLHttpRequest'
    }
    response_code, response = api_request(method="GET", url=url, headers=headers, data=payload)
    logger.info(f"响应内容: {response}")
    logger.info(f'↑↑↑=================================================↑↑↑')
    # 获取目录树数据
    tree_data = response['data']['fields']['category_id']['tree']
    
    # 构建节点映射表：id -> (pId, name)
    node_map = {}
    for node in tree_data:
        node_id = node['id']
        node_map[node_id] = (node['pId'], node['name'])
    
    # 递归函数：生成从根节点到当前节点的路径
    def get_full_path(node_id):
        pId, name = node_map[node_id]
        if pId == '0' or pId not in node_map:  # 根节点或无效父节点
            return name
        else:
            parent_path = get_full_path(pId)
            return f"{parent_path}-{name}"
    
    # 生成目录字典
    dir_dict = {}
    for node_id in node_map:
        full_path = get_full_path(node_id)
        dir_dict[full_path] = node_id
    logger.info(f'目录树数据:\n {dir_dict}')
    # 格式：{'固定目录不要删除': '1148433040001003468', '固定目录不要删除-qwer子目录': '1148433040001003469', '未规划目录': '-1'}
    return response_code,dir_dict
  


if __name__ == "__main__":
    capture_get_dir()